﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using XiaoYuStock.Core.Entities;
using System.Net;
namespace XiaoYuStock.Core
{
    public class DayDataFile
    {
        /// <summary>
        /// 
        /// http://market.finance.sina.com.cn/downxls.php?date=2016-03-31&amp;symbol=sh600106
        /// </summary>
        private static string requestUrl = "http://market.finance.sina.com.cn/downxls.php?date={0}&symbol={1}";


        /// <summary>
        /// 股票代码
        /// </summary>
        public string SharesCode { get; set; }

        /// <summary>
        /// 天
        /// </summary>
        public string Date { get; set; }


        public List<TradeData> GetData()
        {
            List<TradeData> list = new List<TradeData>();
            var url = string.Format(requestUrl, Date, this.SharesCode);
            string file = "tmpExcel.cvs";
            string filePath = HttpContext.Current.Server.MapPath("~/temp/" + file);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
            RequestHelp.DownLoadFile(url, filePath);
            try
            {

                WebClient webClient = new WebClient();
                ;
                using (FileStream fs = File.OpenRead(filePath))
                {
                    StreamReader sr = new StreamReader(fs,Encoding.GetEncoding("GB2312"));

                    string strLine = "";
                    string[] cells = null;
                    int index = 0;
                    while ((strLine = sr.ReadLine()) != null)
                    {
                        index++;
                        if (index == 1)
                            continue;
                        cells = strLine.Split('\t');
                        //创建列
                        TradeData item = new TradeData();
                        item.Time = cells[0].Trim();
                        item.TradePrice = Convert.ToDecimal(cells[1]);
                        item.FloatAmount = Convert.ToDecimal(cells[2].Trim() == "--" ? "0" : cells[2].Trim());
                        item.TradeCount = Convert.ToInt64(cells[3]);
                        item.TradeAmount = Convert.ToDecimal(cells[4]);
                        item.IsBuy = RequestHelp.striphtml(cells[5]) == "买盘";
                        list.Add(item);


                    }
                    sr.Close();
                }
            }
            catch (Exception ex)
            {
            }

            return list;
        }
    }
}
